import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import threading
import time
import os
import random

class ToyCollectorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("玩具拾取控制系统 - 小球、毛绒玩具、蜡笔小新")
        self.root.geometry("850x700")
        
        # 预设三个玩具图片路径
        self.image_paths = [
            r"C:\Users\abc66\Desktop\ball.jpg",  # 小球图片路径
            r"C:\Users\abc66\Desktop\gonk.jpg",  # 毛绒玩具图片路径
            r"C:\Users\abc66\Desktop\figure.jpg"  # 蜡笔小新图片路径
        ]
        
        # 玩具名称标签
        self.toy_names = ["小球", "毛绒玩具", "蜡笔小新"]
        
        # 各玩具拾取目标数
        self.toy_targets = [3, 3, 1]  # 小球3个、毛绒玩具3个、蜡笔小新1个
        
        # 总玩具数（各玩具目标数之和）
        self.total_toys = sum(self.toy_targets)
        
        # 状态变量
        self.reset_state()  # 初始化状态
        
        # 创建UI
        self.create_ui()
        self.load_preset_images()

    def reset_state(self):
        """重置所有状态变量"""
        self.current_count = 0  # 总拾取数量
        self.toy_counts = [0, 0, 0]  # 各玩具拾取数量
        self.is_collecting = False
        self.collection_thread = None

    def create_ui(self):
        # 图片显示区域
        image_frame = ttk.LabelFrame(self.root, text="玩具展示", padding=10)
        image_frame.pack(pady=10, fill=tk.BOTH, expand=True)
        
        self.image_container = ttk.Frame(image_frame)
        self.image_container.pack(pady=10, fill=tk.BOTH, expand=True)
        
        # 进度条容器框架
        self.progress_container = ttk.Frame(self.root)
        self.progress_container.pack(pady=(0, 10), fill=tk.X, padx=20)
        
        # 计数显示区域
        count_frame = ttk.LabelFrame(self.root, text="玩具数量统计", padding=10)
        count_frame.pack(pady=10, fill=tk.X)
        
        # 总体计数
        ttk.Label(count_frame, text="总玩具数:").pack(side=tk.LEFT, padx=10)
        self.total_label = ttk.Label(count_frame, text=str(self.total_toys), font=("Arial", 12, "bold"))
        self.total_label.pack(side=tk.LEFT, padx=5)
        
        ttk.Label(count_frame, text="已拾取:").pack(side=tk.LEFT, padx=(30,10))
        self.collected_label = ttk.Label(count_frame, text="0", font=("Arial", 12, "bold"), foreground="blue")
        self.collected_label.pack(side=tk.LEFT, padx=5)
        
        # 控制按钮区域
        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(pady=20)
        
        self.start_btn = ttk.Button(btn_frame, text="开始拾取", width=12, command=self.start_collection)
        self.start_btn.pack(side=tk.LEFT, padx=10)
        
        self.stop_btn = ttk.Button(btn_frame, text="停止拾取", width=12, command=self.stop_collection, state=tk.DISABLED)
        self.stop_btn.pack(side=tk.LEFT, padx=10)
        
        # 添加复位按钮
        self.reset_btn = ttk.Button(btn_frame, text="复位", width=12, command=self.reset_collection)
        self.reset_btn.pack(side=tk.LEFT, padx=10)
        
        # 状态栏
        self.status_var = tk.StringVar(value="就绪 | 待启动")
        status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
        status_bar.pack(side=tk.BOTTOM, fill=tk.X, pady=5)

    def load_preset_images(self):
        """加载预设图片到UI并创建进度条"""
        # 清空图像容器
        for container in self.image_container.winfo_children():
            container.destroy()
            
        # 清空进度条容器
        for widget in self.progress_container.winfo_children():
            widget.destroy()
        
        # 为每种玩具创建进度条变量
        self.progress_vars = [
            tk.IntVar(value=0) for _ in range(len(self.toy_names))
        ]
        
        # 进度条数值标签引用
        self.progress_count_labels = []
        
        # 进度条标题
        ttk.Label(self.progress_container, text="拾取进度:", font=("Arial", 9, "bold")).pack(anchor=tk.W, pady=(0, 5))
        
        # 图片引用列表（防止垃圾回收）
        self.image_references = []
        
        for i, (name, path) in enumerate(zip(self.toy_names, self.image_paths)):
            # 创建玩具展示框架
            toy_frame = ttk.Frame(self.image_container)
            toy_frame.pack(side=tk.LEFT, padx=15, pady=5, expand=True)
            
            # 玩具名称标签
            name_label = ttk.Label(toy_frame, text=name, font=("Microsoft YaHei", 10, "bold"))
            name_label.pack(pady=(0, 5))
            
            # 尝试加载图片
            image_label = ttk.Label(toy_frame)
            image_label.pack()
            
            try:
                if os.path.exists(path):
                    img = Image.open(path)
                    img.thumbnail((160, 160))
                    photo = ImageTk.PhotoImage(img)
                    image_label.configure(image=photo)
                    self.image_references.append(photo)  # 保持引用
                else:
                    image_label.configure(text=f"图片未找到: {os.path.basename(path)}", foreground="red")
            except Exception as e:
                image_label.configure(text=f"加载失败: {str(e)}", foreground="red")
            
            # 创建玩具进度条框架
            progress_frame = ttk.Frame(self.progress_container)
            progress_frame.pack(fill=tk.X, padx=20, pady=(0, 10))
            
            # 进度条标签
            ttk.Label(progress_frame, text=f"{name}:", width=12).pack(side=tk.LEFT)
            
            # 进度条
            progress = ttk.Progressbar(
                progress_frame, 
                variable=self.progress_vars[i],
                maximum=self.toy_targets[i],
                length=180,
                mode='determinate'
            )
            progress.pack(side=tk.LEFT, expand=True, fill=tk.X)
            
            # 进度数值标签
            count_label = ttk.Label(progress_frame, text=f"0/{self.toy_targets[i]}", width=8)
            count_label.pack(side=tk.LEFT, padx=5)
            self.progress_count_labels.append(count_label)

    def start_collection(self):
        """开始拾取过程"""
        if self.current_count >= self.total_toys:
            self.status_var.set("错误 | 已拾取所有玩具")
            return
            
        self.is_collecting = True
        self.start_btn.config(state=tk.DISABLED)
        self.stop_btn.config(state=tk.NORMAL)
        self.reset_btn.config(state=tk.DISABLED)  # 拾取过程中禁用复位按钮
        self.status_var.set("运行中 | 正在拾取玩具...")
        
        # 启动采集线程
        self.collection_thread = threading.Thread(target=self.collection_process, daemon=True)
        self.collection_thread.start()

    def stop_collection(self):
        """停止拾取过程"""
        self.is_collecting = False
        self.start_btn.config(state=tk.NORMAL)
        self.stop_btn.config(state=tk.DISABLED)
        self.reset_btn.config(state=tk.NORMAL)  # 停止后启用复位按钮
        self.status_var.set("已停止 | 拾取暂停")
        
        # 等待线程结束
        if self.collection_thread and self.collection_thread.is_alive():
            self.collection_thread.join(timeout=1.0)

    def collection_process(self):
        """模拟玩具拾取过程"""
        while self.is_collecting and self.current_count < self.total_toys:
            time.sleep(1)  # 模拟拾取间隔
            
            # 随机选择一个尚未达到目标数的玩具
            available_toys = [i for i in range(3) if self.toy_counts[i] < self.toy_targets[i]]
            if not available_toys:
                break
                
            toy_index = random.choice(available_toys)
            
            # 更新计数
            self.toy_counts[toy_index] += 1
            self.current_count += 1
            
            # 线程安全更新UI
            self.root.after(0, self.update_status, toy_index)
            
            if self.current_count >= self.total_toys:
                self.is_collecting = False
                self.root.after(0, self.complete_collection)

    def update_status(self, toy_index):
        """更新UI状态"""
        # 更新总拾取计数
        self.collected_label.config(text=str(self.current_count))
        
        # 更新具体玩具进度条
        self.progress_vars[toy_index].set(self.toy_counts[toy_index])
        
        # 更新进度条数值标签
        self.progress_count_labels[toy_index].config(
            text=f"{self.toy_counts[toy_index]}/{self.toy_targets[toy_index]}"
        )
        
        # 更新状态栏
        progress = int(self.current_count / self.total_toys * 100)
        self.status_var.set(f"运行中 | 已拾取 {self.current_count}/{self.total_toys} ({progress}%)")
        
        # 当所有玩具都拾取完毕时
        if self.current_count >= self.total_toys:
            self.root.after(0, self.complete_collection)

    def complete_collection(self):
        """完成所有拾取后的操作"""
        self.start_btn.config(state=tk.DISABLED)
        self.stop_btn.config(state=tk.DISABLED)
        self.reset_btn.config(state=tk.NORMAL)  # 完成后启用复位按钮
        self.status_var.set("完成 | 所有玩具已拾取完毕")
        
    def reset_collection(self):
        """复位系统：重置所有计数和状态"""
        # 如果拾取正在进行，先停止
        if self.is_collecting:
            self.stop_collection()
            # 确保线程停止后再继续
            time.sleep(0.2)
        
        # 重置所有计数
        self.reset_state()
        
        # 更新UI显示 - 不需要重新加载图片
        self.collected_label.config(text="0")
        self.status_var.set("复位完成 | 准备重新开始")
        
        # 重置进度条
        for i in range(len(self.toy_names)):
            self.progress_vars[i].set(0)
            self.progress_count_labels[i].config(
                text=f"0/{self.toy_targets[i]}"
            )
        
        # 重置按钮状态
        self.start_btn.config(state=tk.NORMAL)
        self.stop_btn.config(state=tk.DISABLED)
        self.reset_btn.config(state=tk.NORMAL)

if __name__ == "__main__":
    root = tk.Tk()
    app = ToyCollectorApp(root)
    root.mainloop()